package com.gzyz.cheetah.interceptor;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.gzyz.cheetah.annotations.DownloadIntercept;
import com.gzyz.cheetah.entity.table.User;
import com.gzyz.cheetah.util.ThreadLocalUtil;
import com.gzyz.cheetah.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 从token中获取id的拦截器
 *
 * @author xclhove
 */
@Slf4j
public class DownloadInterceptor extends AbstractInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        DownloadIntercept loginIntercept = handlerMethod.getMethod().getAnnotation(DownloadIntercept.class);
        //如果要访问的方法上没有加这个注解，那么就说明这个方法不需要拦截，否则就需要进行拦截
        if (null == loginIntercept) {
            return true;
        }
        Integer id = null;
        //获取请求头中的token
        String token = request.getParameter("token");
        if (StrUtil.isBlank(token)) {
            token = request.getHeader("Authorization");
        }
        //从token中获取id
        try {
            id = TokenUtil.getId(token);
        } catch (Exception e) {
            // id = null
        }
        if (id != null) {
            User user = Db.getById(id, User.class);
            boolean validateSuccess = TokenUtil.validate(token, user.getPassword());
            if (!validateSuccess) {
                id = null;
            }
        }
        //将id存入ThreadLocal
        ThreadLocalUtil.set("id", id);
        return true;
    }
}